<?php

namespace App\System\Base\Services;

use App\System\Base\Helpers\Traits\SinglePattern;
use App\System\Base\Model\BaseImage;
use Illuminate\Support\Facades\Request;
use QCloud\Cos\Api;
use Tencentyun\ImageV2;
use Tencentyun\Image;
use Tencentyun\Auth;
use Tencentyun\Video;
use Tencentyun\ImageProcess;

require_once('../vendor/cos-php-sdk-v4/include.php');

class ImageService extends Service
{
    use SinglePattern;

    public function uploadFilebak($file, $request)
    {
        $file = $file;
        if ($file['Filedata']['error'] == 0 && isset($file['Filedata'])) {
            $exttention = array('image/gif', 'image/jpg', 'image/jpeg', 'image/png');
            //文件类型
            $mimeType = $file['Filedata']['type'];
            if (!in_array(strtolower($mimeType), $exttention)) {
                $error = '文件类型不正确，或未选择上传图片！';
                $path = '';
                $imgid = '';
                $return = array('error' => $error, 'path' => $path, 'image_id' => $imgid);
                return $return;
            }

            //扩展文件名
            $ext = substr($file['Filedata']['name'], strpos($file['Filedata']['name'], '.'));
            //判断文件是否是通过HTTP POST上传的
            $realPath = $file['Filedata']['tmp_name'];
            $content = $this->getUrlImage($realPath);
            $md5 = md5($content);
            $imageInfo = BaseImage::where('md5', $md5)->first();
            $error = '';

            if ($imageInfo) {
                $path = $imageInfo['path'] . $imageInfo['filename'];
                BaseImage::where('id', $imageInfo['id'])->increment('count', 1);
                $imgid = $imageInfo['id'];
            } else {
                $path = date('Ymd/');
                $filename = rand(10000, 99999) . '_' . date('His') . $ext;
                $imageSize = getImageSize($realPath);
                $data['md5'] = $md5;
                $data['filename'] = $filename;
                $data['path'] = $path;
                $data['width'] = $imageSize[0];
                $data['height'] = $imageSize[1];
                $data['count'] = 1;
                $data['user_id'] = 0;
                $imgid = BaseImage::insertGetId($data);
                if (!$imgid) {
                    $error = '上传失败，未知错误！';
                }
                $request->file('Filedata')->storeAs(config('global.upload_path') . $path, $filename);
                $path = config('global.image_path') . $path . $filename;
            }
            $return = array('error' => $error, 'path' => $path, 'image_id' => $imgid);
            return $return;
        }

    }

    public function apiUpload()
    {
        $file_array = Request::file("file");
        if(!$file_array)
        {
            return ['s'=>'1201','d'=>'请上传正确的图片格式'];
        }
        foreach ($file_array as $file)
        {
            $ext = $file->getClientOriginalExtension();

            if(!in_array($ext,['gif','jpg','jpeg','png']))
            {
                return ['s'=>'1201','d'=>'请上传正确的图片格式'];
            }
            $size = $file->getSize();
            if($size > 1024000)
            {
                return ['s'=>'1200','d'=>'上传文件不能超过1M'];
            }
            $realPath = $file->getRealPath();
            $content = $this->getUrlImage($realPath);
            $md5 = md5($content);
            $imageInfo = BaseImage::where('md5', $md5)->first();

            if ($imageInfo)
            {//上传过更新上传次数
                $path = $imageInfo['path'] . $imageInfo['filename'];
                BaseImage::where('id', $imageInfo['id'])->increment('count', 1);
                $imgid = $imageInfo['id'];
            } else {
                $path = date('Ymd').'/';
                $filename = rand(10000, 99999) . '_' . date('His') .'.'. $ext;
                $res = $file->storeAs(config('global.upload_path') . $path, $filename);
                if (!$res) {
                    return ['s'=>'1000','d'=>'图片上传失败'];
                }
                $imageSize = getImageSize($realPath);
                $data['md5'] = $md5;
                $data['filename'] = $filename;
                $data['path'] = $path;
                $data['width'] = $imageSize[0];
                $data['height'] = $imageSize[1];
                $data['count'] = 1;
                $data['user_id'] = 0;
                $imgid = BaseImage::create($data);
                if (!$imgid) {
                    return ['s'=>'1000','d'=>'图片上传失败'];
                }
                $imgid = $imgid->id;
                $path = config('global.image_path') . $path . $filename;
            }

            $return['files'][] = ['path' => $path, 'id' => $imgid];
        }

        return $return;
    }

    /**判断图片是否上传过
     * @param $path  图片路径
     * @return bool|mixed|string
     */
    protected function getUrlImage($path)
    {
        if (preg_match('/http\:\/\//i', $path)) {
            $cookie_file = tempnam('./temp', 'cookie');
            $url = $path;
            $ch = curl_init($url);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
            $content = curl_exec($ch);
        } else {
            $content = file_get_contents($path);
        }
        return $content;
    }
}